﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.ComponentModel.DataAnnotations;
using System.IO;
using Decembre.Controllers;
namespace Decembre.Models
{   
    public class Membre
    {
        public string ID { get; set; }
        [Required]
        public string NOM { get; set; }
        public string PRENOM { get; set; }
        public DateTime DATE_NAISSANCE { get; set; }
        public DateTime DATE_INSCRIPTION { get; set; }
        public bool ACTIF { get; set; }
        public string TELEPHONE { get; set; }
        public string EMAIL { get; set; }
        public string PHOTOS { get; set; }
        public string ADRESSE { get; set; }
        public string DESCRIPTION { get; set; }
        public string ANTONY { get; set; }
    }
    public class Membres
    {
        private SqlConnection con = null;
        private SqlCommand cmd = null;
        private DataTable dt = null;
        private bool inuse = false;
        public bool inUse
        {
            get { return inuse; }
        }
        //requête SELECT
        public Membres(out List<Membre> data)
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnex"].ConnectionString);
            try
            {
                con.Open();
                cmd = new SqlCommand();
                cmd.CommandText = "select * from MEMBRES order by (NOM) DESC";
                cmd.Connection = con;
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    string id, nom, prenom, email, telephone,photos;
                    DateTime date_inscription,date_naissance;
                    bool actif;
                    data = new List<Membre>();
                    while (reader.Read())
                    {
                        id = reader.GetString(0);
                        nom = reader[1]==DBNull.Value?"":reader.GetString(1);
                        prenom = reader[2]==DBNull.Value?"":reader.GetString(2);
                        date_naissance=reader[3]==DBNull.Value?new DateTime():reader.GetDateTime(3);
                        date_inscription=reader[4]==DBNull.Value?new DateTime():reader.GetDateTime(4);
                        actif=reader.GetBoolean(5);
                        telephone=reader[6]==DBNull.Value?"":reader.GetString(6);
                        email=reader[7]==DBNull.Value?"":reader.GetString(7);
                        photos = reader.GetString(8);
                        data.Add(new  Membre{ID=id,NOM=nom,PRENOM=prenom,DATE_NAISSANCE=date_naissance,DATE_INSCRIPTION=date_inscription,ACTIF=actif,TELEPHONE=telephone,EMAIL=email,PHOTOS=photos});
                    }                    
                }
                else
                    data = null;
            }
            catch (SqlException e)
            {
                data = null;
                StreamWriter wr = new StreamWriter("myAppLog", true);
                wr.WriteLine(e.Server + ":" + e.Message);
                wr.Close();
            }
            con.Close();
        }
        //requête update ou insert
        public Membres(Membre up,AdminController ctr,bool update=true)
        {
            string id;
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnex"].ConnectionString);
            try
            {
                con.Open();
                cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@nom", up.NOM);
                cmd.Parameters.AddWithValue("@prenom", up.PRENOM);
                cmd.Parameters.AddWithValue("@d1", up.DATE_NAISSANCE);
                cmd.Parameters.AddWithValue("@d2", up.DATE_INSCRIPTION);
                cmd.Parameters.AddWithValue("@actif", up.ACTIF);
                cmd.Parameters.AddWithValue("@phone", up.TELEPHONE);
                cmd.Parameters.AddWithValue("@mail", up.EMAIL);
                cmd.Parameters.AddWithValue("@adr", up.ADRESSE);
                cmd.Parameters.AddWithValue("@desc", up.DESCRIPTION);
                cmd.Parameters.AddWithValue("@antony", up.ANTONY);                
                if (update)
                {
                    cmd.Parameters.AddWithValue("@id", up.ID);
                    id = up.ID;
                    cmd.CommandText = "update MEMBRES set NOM=@nom,PRENOM=@prenom,DATE_NAISSANCE=@d1" +
                    ",DATE_INSCRIPTION=@d2,ACTIF=@actif,TELEPHONE=@phone,EMAIL=@mail,ADRESSE=@adr,DESCRIPTION=@desc where ID=@id";
                    int res=cmd.ExecuteNonQuery();
                    if (res > 0)
                        inuse = true;
                }
                else
                {
                    string dest=null;
                    cmd.CommandText = "select STK_MEMBRE from PARAMS_STK";
                    id = cmd.ExecuteScalar() == null ? "" : (string)cmd.ExecuteScalar();
                    if (id == "")
                    {
                        id = "STK_0001";
                        cmd.CommandText = "insert into PARAMS_STK (STK_MEMBRE) values ('" + id + "')";
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        id = string.Format("STK_{0:0000}", (Convert.ToInt32(id.Split('_')[1]) + 1));
                        cmd.CommandText = "update PARAMS_STK set STK_MEMBRE='" + id + "'";
                        cmd.ExecuteNonQuery();
                    }
                    //création dossier propre à l'utilisateur crée
                    if (ctr.Session["file_importer"] != null)//normalement non null
                    {
                        string file_name = (string)ctr.Session["file_importer"];
                        ctr.Session.Remove("file_importer");
                        if (!Directory.Exists(ctr.Server.MapPath("~/Users/" + id)))
                            Directory.CreateDirectory(ctr.Server.MapPath("~/Users/" + id));
                        Directory.CreateDirectory(ctr.Server.MapPath("~/Users/" + id + "/Images"));
                        if (File.Exists(file_name))
                        {
                            FileInfo ext = new FileInfo(file_name);
                            dest = ctr.Server.MapPath("~/Users/" + id + "/Images/" + id + "_curpro" + ext.Extension);
                            string dest_serveur = "/Users/" + id + "/Images/" + id + "_curpro" + ext.Extension;
                            File.Move(file_name, dest);
                            cmd.Parameters.AddWithValue("@photos", dest_serveur);
                        }
                    }
                    cmd.CommandText = "insert into MEMBRES values ('" + id + "',@nom,@prenom,@d1,@d2,@actif,@phone,@mail,"+(dest==null?"default":"@photos")+",@adr,@desc,@antony)";
                    int res = cmd.ExecuteNonQuery();
                    if (res > 0)
                    {
                        inuse = true;                        
                    }
                }                
            }
            catch (SqlException e)
            {
                StreamWriter wr = new StreamWriter("myAppLog", true);
                wr.WriteLine(e.Server + ":" + e.Message);
                wr.Close();
            }
            con.Close();
        }        
    }
}